<template>
  <el-form
    class="apply-form"
    :rules="rules"
    ref="apply-form"
    :model="form"
  >
    <el-steps
      :active="active"
      finish-status="success"
      align-center
      style="margin-top: 20px"
    >
      <el-step title="基本信息"></el-step>
      <el-step title="联系方式"></el-step>
      <el-step title="个人介绍"></el-step>
      <el-step title="完成编辑"></el-step>
      <el-step title="提交成功"></el-step>
    </el-steps>

    <el-card shadow="never">
      <transition name="shit">

        <div
          class="step"
          v-show="active === 0"
        >
          <h3>基本信息</h3>
          <section class="base-info">
            <div class="base-info-avatar-upload">
              <el-form-item label="生活照">
                <OSSUpload
                  :imageUrl="form.portrait"
                  @success="handleAvatarUploadSuccess"
                  path="apply"
                  region="oss-cn-shenzhen"
                  bucket="tidc-drive"
                  ossTokenUrl="https://java.cx-tidc.com/manage/ossToken/"
                ></OSSUpload>
              </el-form-item>
            </div>

            <div class="base-info-input-group">
              <el-form-item
                label="姓名"
                prop="name"
              >
                <el-input
                  v-model="form.name"
                  placeholder="填写你的名字"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="班级"
                prop="className"
              >
                <el-input
                  v-model="form.className"
                  placeholder="填写你的班级"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="学号"
                prop="studentId"
              >
                <el-input
                  v-model="form.studentId"
                  placeholder="填写你的学号"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="性别"
                prop="gender"
              >
                <el-radio-group v-model.number="form.gender">
                  <el-radio
                    :label="1"
                    border
                  >男生</el-radio>
                  <el-radio
                    :label="2"
                    border
                  >女生</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </section>
        </div>
      </transition>

      <transition name="shit">
        <div
          class="step"
          v-show="active === 1"
        >
          <h3>联系方式</h3>
          <section class="contact-info">
            <el-form-item
              label="手机号"
              prop="phoneNumber"
            >
              <el-input
                v-model="form.phoneNumber"
                placeholder="手机号"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="微信号"
              prop="wechat"
            >
              <el-input
                v-model="form.wechat"
                placeholder="微信号"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="邮箱"
              prop="email"
            >
              <el-input
                v-model="form.email"
                placeholder="邮箱"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="个人主页"
              prop="blogUrl"
            >
              <el-input
                v-model="form.blogUrl"
                placeholder="选填；可以是你的个人博客地址，也可以是GitHub、Gitee"
              ></el-input>
            </el-form-item>
          </section>
        </div>
      </transition>

      <transition name="shit">
        <div
          class="step"
          v-show="active === 2"
        >
          <h3>学习情况</h3>
          <section class="direction-info">
            <el-form-item
              label="主攻方向 "
              prop="major"
            >
              <el-autocomplete
                v-model="form.major "
                :fetch-suggestions="autoMajor"
                placeholder="选填；填写或选择你的主攻方向"
              ></el-autocomplete>
            </el-form-item>
            <el-form-item
              :label="`自我介绍 | ${introduceSize}/200字`"
              prop="introduce"
            >
              <el-input
                type="textarea"
                :autosize="{ minRows: 5, maxRows: 5}"
                placeholder="请输入30到200字的自我介绍"
                v-model="form.introduce"
              >
              </el-input>
            </el-form-item>
          </section>
        </div>
      </transition>

      <transition name="shit">
        <div
          class="step"
          style="text-align: center; padding-bottom: 22px;"
          v-show="active === 3"
        >
          <h1><i
              class="el-icon-success"
              style="color: #67C23A; margin: 8px;"
            ></i>完成了</h1>

          <el-form
            label-position="left"
            inline
            id="apply-form-preview"
          >
            <el-form-item label="姓名">
              <span>{{ form.name }}</span>
            </el-form-item>
            <el-form-item label="性别">
              <span v-if="form.gender === 1">男</span>
              <span v-if="form.gender === 2">女</span>
            </el-form-item>
            <el-form-item label="班级">
              <span>{{ form.className }}</span>
            </el-form-item>
            <el-form-item label="学号">
              <span>{{ form.studentId }}</span>
            </el-form-item>

            <el-form-item label="电话">
              <span>{{ form.phoneNumber }}</span>
            </el-form-item>
            <el-form-item label="WeChat">
              <span>{{ form.wechat }}</span>
            </el-form-item>
            <el-form-item label="邮箱">
              <span>{{ form.email }}</span>
            </el-form-item>

            <el-form-item label="学习方向">
              <span>{{ form.major }}</span>
            </el-form-item>

            <el-form-item label="自我介绍">
              <el-card
                :body-style="{padding: '0'}"
                style="margin: 0; max-width: 480px; border: 0;"
                shadow="never"
              >
                {{ form.introduce }}
              </el-card>
            </el-form-item>
          </el-form>

          <el-row>
            <el-button
              :loading=" loading"
              type="primary"
              @click="onSubmit('apply-form')"
            >提交申请</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-row>
        </div>
      </transition>

      <transition name="shit">
        <div
          class="step"
          style="text-align: center; padding-bottom: 22px;"
          v-show="active === 4"
        >
          <h1><i
              class="el-icon-info"
              style="color: #409EFF; margin: 8px;"
            ></i>祝你好运✨</h1>
        </div>
      </transition>
    </el-card>

    <el-row class="step-option">
      <el-button
        :disabled="active === 0 || active > 3"
        @click="prevStep"
      >上一步</el-button>
      <el-button
        :disabled="active > 2"
        type="primary"
        @click="nextStep"
      >下一步</el-button>
    </el-row>

  </el-form>
</template>

<script>
// import { REQUEST_STATUS } from "../utils/constants";
import storage from "../utils/storage";
import api from "@/api.js";
import OSSUpload from "./OSSUpload";

const EMPTY_APPLY_FORM = {
  name: "",
  className: "",
  studentId: "",
  gender: "",
  portrait: "",
  phoneNumber: "",
  wechat: "",
  email: "",
  major: "",
  introduce: ""
};

export default {
  components: {
    OSSUpload
  },
  data() {
    return {
      name: "apply-form",
      loading: false,
      active: 0,
      form: {
        name: "",
        className: "",
        studentId: "",
        gender: "",
        portrait: "",
        phoneNumber: "",
        wechat: "",
        email: "",
        major: "",
        introduce: ""
      },
      fields: [
        ["name", "className", "studentId", "gender"],
        ["phoneNumber", "wechat", "email"],
        ["major", "introduce"]
      ],
      rules: {
        name: [
          { required: true, message: "请输入你的名字", trigger: "blur" },
          { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: "只能是长度2到5的中文字符", trigger: "blur" },
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        className: [
          { required: true, message: "请输入你的班级", trigger: "blur" },
          { pattern: /^\d{2}[\u4E00-\u9FA5]{2}\d{1,2}班$/, message: "请输入正确的班级，例如 18计应1班", trigger: "blur" },
        ],
        studentId: [
          { required: true, message: "请输入你的学号", trigger: "blur" },
          { pattern: /^[1-9]\d0\d{3}[0-1][1-9][0-5]\d$/, message: "请输入正确的学号", trigger: "blur" },
        ],

        phoneNumber: [
          { required: true, message: "请输入你的手机号", trigger: "blur" },
          {
            pattern: /^((1[3-8][0-9])+\d{8})$/,
            message: "请输入正确的手机号",
            trigger: "blur"
          },
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: "请输入正确的邮箱", trigger: "blur" }
        ],
        wechat: [
          { required: true, message: "请输入你的微信号", trigger: "blur" },
          // { pattern: /^([a-zA-Z][-_a-zA-Z0-9]{5,19})|(1[3-9]\\d{9})$/, message: "请输入正确的微信号", trigger: "blur" }
        ],

        major: [
          { max: 64, message: "太多了", trigger: "blur" }
        ],
        introduce: [
          { required: true, message: "请输入你的个人简介", trigger: "blur" },
          { min: 30, message: "最少30字噢，请认真填写", trigger: "blur" },
          { max: 200, message: "太多了，不要超过200字", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    introduceSize() {
      return this.form.introduce.length;
    }
  },
  created() {
    const formData = storage.get(this.name);
    if (formData !== null) {
      this.form = formData;
    }
  },
  watch: {
    form: {
      deep: true,
      handler: function (val) {
        storage.set(this.name, val);
      }
    }
  },
  methods: {
    autoMajor(qs, cb) {
      cb([
        { value: "算法竞赛" },
        { value: "前端开发" },
        { value: "后端开发" },
        { value: "PHP开发" },
        { value: "UI设计" },
        { value: "移动开发" },
        { value: "测试" },
        { value: "运维/技术支持" },
        { value: "数据" },
        { value: "硬件开发" },
        { value: "电子/半导体" },
        { value: "人工智能" },
      ]);
    },
    handleAvatarUploadSuccess(url) {
      this.form.portrait = url;
    },
    validateForm() {
      const formName = this.name;
      let validResult = false;
      this.$refs[formName].validate(valid => {
        if (valid) {
          validResult = true;
        } else {
          validResult = false;
        }
      });
      return validResult;
    },
    async onSubmit() {
      if (!this.validateForm()) {
        return;
      }
      this.loading = true;

      const grade = `20${this.form.className.substring(0, 2)}`;
      // .replace(/\n/g, '，')
      // const introduce = this.form.introduce.replace(/\n/g, '，');
      let form = {
        ...this.form,
        grade,
        // introduce
      };
      try {
        await api.submitApplyForm(form);
        this.$message({
          showClose: true,
          message: "恭喜你，提交成功",
          type: "success"
        });
        this.resetForm();
        this.active = 4;
      } catch (error) {
        this.$message({
          showClose: true,
          message: `提交失败，${JSON.stringify(error.response.data.msg)}`,
          type: "error"
        });
      }
      this.loading = false;
    },
    resetForm() {
      this.active = 0;
      const formName = this.name;

      // 不知道什么原因 无法正常清空表单
      this.$refs[formName].resetFields();
      // 采用弱智方法清空
      this.form = EMPTY_APPLY_FORM;
      storage.remove(this.name);
    },
    nextStep() {
      const fields = this.fields[this.active];
      let ok = true;
      for (const field of fields) {
        this.$refs[this.name].validateField(field, err => {
          if (err !== "") {
            ok = false
          }
        });
      }

      if (ok && this.active < 3) {
        this.active++;
      }
    },
    prevStep() {
      if (this.active > 0) {
        this.active--;
      }
    },
  }
};
</script>

<style lang="scss">
.apply-form {
  margin: 0 auto;
  width: auto;
  max-width: 640px;
  section {
    box-sizing: border-box;
    padding: 0 16px;
  }
}

.base-info-input-group {
  margin-right: 25px;
  order: -1;
}
@media (orientation: portrait) and (max-width: 625px) {
  .base-info-input-group {
    order: 10;
  }
}

.base-info-avatar-upload {
  width: 192px;
  .oss-upload {
    width: 192px;
  }
}

h3 {
  margin: 0 auto 25px;
  padding: 0 0 8px 0;
  max-width: 960px;
  text-align: left;
  color: #909399;
  border-bottom: 1px dotted #c0c4cc;
}
.el-card {
  margin: 25px 0;
}

.base-info,
.contact-info {
  display: flex;
  flex-wrap: wrap;

  .el-form-item {
    max-width: 455px;
  }
}

.el-radio.is-bordered {
  width: 106px;
  padding-left: 23px;
}

.el-autocomplete,
.el-form-item {
  width: 100%;
  min-width: 320px;
}

.el-form-item__label {
  text-align: right;
}
.step-option {
  & > * {
    width: 50%;
  }
  .el-button + .el-button {
    margin: 0;
  }
}

#apply-form-preview {
  font-size: 0;
  text-align: left;
  .el-form-item {
    box-sizing: border-box;
    padding: 0 8px;
    margin-right: 0;
    margin-bottom: 0;
  }
  label {
    width: 90px;
    color: #99a9bf;
  }
}
</style>

<style>
.step {
  width: 100%;
}
.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  left: 5px;
  overflow: hidden;
}
.el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.shit-enter-active {
  transition: all 0.4s;
}
.shit-enter,
.shit-leave-to {
  opacity: 0;
  filter: blur(4px);
  transform: translateY(35px);
}
.shit-leave {
  display: none;
}
</style>
